package edu.controller;

import edu.service.RolePermissionService;
import edu.vo.RolePermission;
import edu.vo.ID.RolePermissionId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/role-permissions")
public class RolePermissionController {

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 保存角色权限关联信息
     * @param rolePermission 角色权限关联对象
     * @return 保存后的角色权限关联对象
     */
    @PostMapping
    public ResponseEntity<RolePermission> saveRolePermission(@RequestBody RolePermission rolePermission) {
        RolePermission savedRolePermission = rolePermissionService.saveRolePermission(rolePermission);
        return new ResponseEntity<>(savedRolePermission, HttpStatus.CREATED);
    }

    /**
     * 根据ID获取角色权限关联信息
     * @param id 角色权限关联ID
     * @return 角色权限关联对象的Optional包装
     */
    @GetMapping("/{id}")
    public ResponseEntity<RolePermission> getRolePermissionById(@PathVariable RolePermissionId id) {
        Optional<RolePermission> rolePermission = rolePermissionService.getRolePermissionById(id);
        return rolePermission.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 获取所有角色权限关联信息
     * @return 角色权限关联列表
     */
    @GetMapping
    public ResponseEntity<List<RolePermission>> getAllRolePermissions() {
        List<RolePermission> rolePermissions = rolePermissionService.getAllRolePermissions();
        return new ResponseEntity<>(rolePermissions, HttpStatus.OK);
    }

    /**
     * 根据ID删除角色权限关联信息
     * @param id 角色权限关联ID
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteRolePermissionById(@PathVariable RolePermissionId id) {
        rolePermissionService.deleteRolePermissionById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 更新角色权限关联信息
     * @param id 角色权限关联ID
     * @param rolePermission 新的角色权限关联信息
     * @return 更新后的角色权限关联对象
     */
    @PutMapping("/{id}")
    public ResponseEntity<RolePermission> updateRolePermission(@PathVariable RolePermissionId id, @RequestBody RolePermission rolePermission) {
        RolePermission updatedRolePermission = rolePermissionService.updateRolePermission(id, rolePermission);
        return updatedRolePermission != null ? new ResponseEntity<>(updatedRolePermission, HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}